package com.xunqi.usercenter.controller;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import com.xunqi.common.dto.user.JwtTokenResponseDTO;
import com.xunqi.common.dto.user.LoginResponseDTO;
import com.xunqi.common.dto.user.UserLoginDTO;
import com.xunqi.common.dto.user.UserResponseDTO;
import com.xunqi.common.entity.user.User;
import com.xunqi.common.util.JwtOperator;
import com.xunqi.usercenter.service.UserService;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

/**
 * @Description:
 * @Created with IntelliJ IDEA.
 * @author: 夏沫止水
 * @create: 2020-04-17 10:56
 **/
@RestController
@RequestMapping(value = "/users")
@Slf4j
public class UserController {

    @Resource
    private UserService userService;

    @Resource
    private WxMaService wxMaService;

    @Resource
    private JwtOperator jwtOperator;

    @GetMapping(value = "/{id}")
    public User findById(@PathVariable("id") Integer id) {
        return userService.findById(id);
    }


    /**
     * 模拟生成token
     * @return
     */
    @GetMapping(value = "/gen/token")
    public String getToken() {
        Map<String,Object> userInfoMap = new HashMap<>();
        userInfoMap.put("id",1);
        userInfoMap.put("wxNickName","夏沫止水");
        userInfoMap.put("role","admin");
        return this.jwtOperator.generateToken(userInfoMap);
    }


    @PostMapping(value = "/login")
    public LoginResponseDTO login(@RequestBody UserLoginDTO loginDTO) throws WxErrorException {

        //微信小程序服务端检验是否已经登录的结果
        WxMaJscode2SessionResult result = this.wxMaService.getUserService()
                .getSessionInfo(loginDTO.getCode());

        //微信的openID，用户在微信这边的唯一标识
        String openid = result.getOpenid();

        //看用户是否注册，没有注册则插入一条消息
        User user = this.userService.login(loginDTO, openid);

        //颁发token
        Map<String,Object> userInfoMap = new HashMap<>();
        userInfoMap.put("id",user.getId());
        userInfoMap.put("wxNickName",user.getWxNickname());
        userInfoMap.put("role",user.getRoles());

        //获取token
        String token = this.jwtOperator.generateToken(userInfoMap);


        log.info(
                "用户{}登录成功，生成的token={},有效期到：{}",
                loginDTO.getWxNickname(),
                token,
                jwtOperator.getExpirationTime()
        );

        return LoginResponseDTO.builder()
                .user(
                        UserResponseDTO.builder()
                                .id(user.getId())
                                .avatarUrl(user.getAvatarUrl())
                                .bonus(user.getBonus())
                                .wxNickname(user.getWxNickname())
                                .build()
                )
                .token(
                        JwtTokenResponseDTO.builder()
                                .expirationTime(jwtOperator.getExpirationTime().getTime())
                                .token(token)
                                .build()
                )
                .build();
    }

}
